package com.android.kotlincoroutinemvvmdemo.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.util.AttributeSet
import com.android.kotlincoroutinemvvmdemo.R

/*
* VoiceView
* */
class VoiceView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : BaseView(context, attributeSet) {

    private val mPaint0 by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            strokeCap = Paint.Cap.ROUND
            strokeJoin = Paint.Join.ROUND
            style = Paint.Style.STROKE
            color = context.resources.getColor(R.color.color_7D4FE3)
        }
    }

    private val mPaint1 by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            color = context.resources.getColor(R.color.color_7D4FE3)
        }
    }

    private val mPaint2 by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            color = context.resources.getColor(R.color.color_E88DBF)
        }
    }

    private val mPath by lazy {
        Path()
    }

    private val mXfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        setBackgroundColor(context.resources.getColor(R.color.color_F3F3F3))
        canvas?.apply {
            val cx = mWidth.toFloat() / 2
            val cy = mHeight.toFloat() / 2
            save()
            translate(cx, cy)

            mPaint0.strokeWidth = cx / 15
            mPath.apply {
                arcTo(
                    -cx * 4 / 7,
                    -cy * 5 / 7,
                    cx * 4 / 7,
                    cy * 3 / 7,
                    0F,
                    180F,
                    true
                )

                moveTo(0F, cy * 3 / 7)
                lineTo(0F, cy)
            }
            drawPath(mPath, mPaint0)

            val layerId = saveLayer(
                -cx * 2 / 7,
                -cy * 6 / 7,
                cx * 2 / 7,
                cy * 2 / 7,
                null)

            drawRoundRect(
                -cx * 2 / 7,
                -cy * 6 / 7,
                cx * 2 / 7,
                cy * 2 / 7,
                cx / 3,
                cy / 3,
                mPaint1
            )

            mPaint2.xfermode = mXfermode
            drawRect(
                -cx * 2 / 7,
                -cy * 1 / 7,
                cx * 2 / 7,
                cy * 2 / 7,
                mPaint2)
            mPaint2.xfermode = null
            restoreToCount(layerId)

            restore()
        }
    }
}